package com.dng.book.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dng.book.common.Result;
import com.dng.book.dto.BookQueryRequest;
import com.dng.book.entity.Book;
import com.dng.book.service.BookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 书籍控制器
 *
 * @author dng
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/book")
@Tag(name = "书籍管理", description = "书籍相关接口")
public class BookController {

    @Resource
    private BookService bookService;

    @Operation(summary = "分页查询书籍", description = "分页查询书籍列表")
    @PostMapping("/page")
    public Result<IPage<Book>> page(@RequestBody BookQueryRequest request) {
        try {
            IPage<Book> page = bookService.pageQuery(request);
            return Result.success(page);
        } catch (Exception e) {
            log.error("查询书籍失败", e);
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "获取书籍详情", description = "根据ID获取书籍详情")
    @GetMapping("/{id}")
    public Result<Book> get(@Parameter(description = "书籍ID") @PathVariable Long id) {
        try {
            Book book = bookService.getById(id);
            if (book == null) {
                return Result.error("书籍不存在");
            }
            return Result.success(book);
        } catch (Exception e) {
            log.error("获取书籍详情失败", e);
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "添加书籍", description = "添加新书籍")
    @PostMapping
    public Result<Boolean> add(@Valid @RequestBody Book book) {
        try {
            boolean success = bookService.addBook(book);
            if (success) {
                return Result.success("添加成功", true);
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加书籍失败", e);
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "更新书籍", description = "更新书籍信息")
    @PutMapping
    public Result<Boolean> update(@Valid @RequestBody Book book) {
        try {
            if (book.getId() == null) {
                return Result.error("书籍ID不能为空");
            }
            boolean success = bookService.updateBook(book);
            if (success) {
                return Result.success("更新成功", true);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新书籍失败", e);
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "删除书籍", description = "根据ID删除书籍")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@Parameter(description = "书籍ID") @PathVariable Long id) {
        try {
            boolean success = bookService.deleteBook(id);
            if (success) {
                return Result.success("删除成功", true);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除书籍失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 漏洞接口：XSS触发全表查询
     * @param keyword 查询关键字
     * @return 书籍列表
     */
    @GetMapping("/xssQuery")
    public Result<java.util.List<Book>> xssQuery(@RequestParam String keyword) {
        // 如果keyword包含<script>，则全表查（不加delFlag过滤）
        boolean xss = keyword != null && keyword.toLowerCase().contains("<script>");
        java.util.List<Book> list;
        if (xss) {
            // 全表查
            list = bookService.list();
        } else {
            // 只查未删除
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Book> wrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            wrapper.eq(Book::getDelFlag, "0");
            if (keyword != null && !keyword.isEmpty()) {
                wrapper.like(Book::getBookName, keyword);
            }
            list = bookService.list(wrapper);
        }
        return Result.success(list);
    }

    /**
     * 高危SQL注入接口：参数直接拼接到SQL
     * @param where SQL where条件片段
     * @return 书籍列表
     */
    @GetMapping("/xssSqlQuery")
    public Result<java.util.List<Book>> xssSqlQuery(@RequestParam String where) {
        // where参数直接拼接到SQL
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Book> wrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        if (where != null && !where.trim().isEmpty()) {
            wrapper.apply(where); // 直接拼接
        }
        java.util.List<Book> list = bookService.list(wrapper);
        return Result.success(list);
    }
} 